import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "TestServlet", value = "/TestServlet")
public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();
        boolean flag = false;
        if (cookies != null && cookies.length > 0 ){
            for (Cookie cookie:cookies) {
                String name = cookie.getName();
                if (name.equals("Counter")) {
                    flag = true;
                    Integer count = Integer.valueOf(cookie.getValue());
                    count++;
                    if (count == 1){
                        out.println("欢迎首次光临");
                    } else {
                        out.println("您已经光临了" + count + "次");
                    }
                    cookie.setValue(String.valueOf(count));
                    cookie.setMaxAge(60*30*24*30);
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        if (cookies == null || cookies.length == 0 || flag == false){
            Integer count = 1;
            Cookie cookie = new Cookie("Counter",String.valueOf(count));
            cookie.setMaxAge(60*30*24*30);
            response.addCookie(cookie);
            out.println("欢迎首次光临");
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
